package fr.sedoo.metadata.client.ui.widget.field.impl;

import java.util.Iterator;
import java.util.List;

import fr.sedoo.commons.client.util.ElementUtil;
import fr.sedoo.commons.client.util.StringUtil;
import fr.sedoo.metadata.client.message.MetadataMessage;
import fr.sedoo.metadata.client.ui.widget.field.constant.FieldConstant;
import fr.sedoo.metadata.client.ui.widget.field.primitive.ListBoxField;
import fr.sedoo.metadata.shared.domain.MetadataDTO;
import fr.sedoo.metadata.shared.domain.misc.Iso6392LanguageProvider;

public class MetadataLanguage extends ListBoxField {
	private List<String> languages;

	public MetadataLanguage(List<String> languages) {
		super();
		this.languages = languages;
		init();
	}

	/**
	 * Build the list box with the editing languages defined in the client
	 * factory
	 */
	private void init() {
		listBox.clear();
		listBox.addItem(MetadataMessage.INSTANCE.selectItem(), FieldConstant.UNSELECTED_ID);
		Iterator<String> iterator = languages.iterator();
		while (iterator.hasNext()) {
			String code = iterator.next();
			String label = Iso6392LanguageProvider.getDisplayNameFromCode(code);
			listBox.addItem(label, code);
		}
	}

	@Override
	public void display(MetadataDTO metadata) {
		ElementUtil.show(label);
		ElementUtil.hide(listBox);
		String aux = StringUtil.trimToEmpty(metadata.getOtherPart().getMetadataLanguage());
		if (StringUtil.isNotEmpty(aux)) {
			aux = Iso6392LanguageProvider.getDisplayNameFromCode(aux);
		}
		label.setText(aux);
	}

	@Override
	public void flush(MetadataDTO metadata) {
		if (listBox.getSelectedIndex() == UNSELECTED_ID_INDEX) {
			metadata.getOtherPart().setMetadataLanguage("");
		} else {
			metadata.getOtherPart().setMetadataLanguage(listBox.getValue(listBox.getSelectedIndex()));
		}
	}

	@Override
	public void edit(MetadataDTO metadata) {
		ElementUtil.show(listBox);
		ElementUtil.hide(label);
		String aux = StringUtil.trimToEmpty(metadata.getOtherPart().getMetadataLanguage());
		if (aux.length() > 0) {
			selectByValue(aux);
		} else {
			listBox.setSelectedIndex(UNSELECTED_ID_INDEX);
		}
	}

}
